<template>
  <div>
    <div style="margin-bottom: 15px">
      <el-input placeholder="请输入内容" style="width: 200px" v-model="input" clearable></el-input>
      <el-button type="warning" style="margin-left: 10px">查询</el-button>
      <el-button type="primary" style="margin-left: 10px" @click="add()">新增</el-button>
    </div>
    <div>
      <el-table :data="tableData" style="width: 100%" :default-sort="{ prop: 'date', order: 'descending' }">
        <el-table-column prop="plaName" label="选手名称" width="200"></el-table-column>
        <el-table-column prop="plaGender" label="性别" width="220"></el-table-column>
        <el-table-column prop="plaDepartment" label="部门" width="260"></el-table-column>
        <el-table-column prop="plaState" label="状态" width="260"></el-table-column>
        <el-table-column prop="plaAvatar" label="头像" sortable width="260" plain @click="startScore(scope.row)">
          <template slot-scope="scope">
            <el-popover placement="top-start" trigger="hover">
              <img :src="scope.row.plaAvatar" style="width: 100px;height: 100px">
              <img :src="scope.row.plaAvatar" slot="reference" style="width: 50px;height: 50px;">
            </el-popover>
          </template>
        </el-table-column>
        <el-table-column prop="plaDate" label="创建时间" sortable width="260"></el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button type="primary" @click="edit(scope.row)">编辑</el-button>
            <el-popconfirm title="确定删除吗？" @confirm="del(scope.row.id)">
              <el-button slot="reference" type="danger" style="margin-left: 5px">删除</el-button>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div style="margin-left: 50%;margin-top: 10px">
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage4"
        :page-sizes="[10, 20, 30, 40]" :page-size="100" layout="total, sizes, prev, pager, next, jumper" :total="20">
      </el-pagination>
    </div>
    <div>
      <!-- Form -->
      <el-dialog title="请填写信息" :visible.sync="dialogFormVisible" width="40%">
        <el-form :model="form" ref="formRef" :rules="rules" label-width="15%" :inline-message="true"
          style="padding: 20px;">
          <el-form-item label="选手姓名" prop="plaName">
            <el-input v-model="form.plaName" placeholder="请输入选手姓名" autocomplete="off" style="width: 80%"></el-input>
          </el-form-item>
          <el-form-item label="性别" prop="plaGender">
            <el-radio v-model="form.plaGender" label="男">男</el-radio>
            <el-radio v-model="form.plaGender" label="女">女</el-radio>
          </el-form-item>
          <el-form-item label="部门" prop="plaDepartment">
            <el-select v-model="form.plaDepartment" placeholder="请选择部门" style="width: 80%">
              <el-option label="星屹一部" value="星屹一部"></el-option>
              <el-option label="晨曦二部" value="晨曦二部"></el-option>
              <el-option label="绪风三部" value="绪风三部"></el-option>
              <el-option label="磐创四部" value="磐创四部"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="状态" prop="plaState">
            <el-radio v-model="form.plaState" label="1">参赛</el-radio>
            <el-radio v-model="form.plaState" label="0">未参赛</el-radio>
          </el-form-item>
          <el-form-item label="头像" prop="plaAvatar" >
            <el-upload class="avatar-uploader" :action="uploadUrl" :show-file-list="false"
              :on-success="handleAvatarSuccess" :before-upload="beforeUpload">
              <img v-if="form.plaAvatar" :src="form.plaAvatar" class="avatar">
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-form-item>
          <!-- =================== -->
          <el-form-item label="风采照" prop="plaPhoto" >
            <el-upload class="avatar-uploader" :action="uploadUrl" :show-file-list="false"
              :on-success="handleAvatarSuccess1" :before-upload="beforeUpload">
              <img v-if="form.plaPhoto" :src="form.plaPhoto" class="avatar">
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-form-item>
          <!-- =========== -->
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="submit()">确 定</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import request from "@/utils/request";
import config from "@/config/env.js";

export default {
  name: "Playerscore",
  data() {
    return {
      uploadUrl: `${config.apiUrl}/common/upload`,
      input: '',
      currentPage4: 4,
      tableData: [],
      dialogFormVisible: false,
      form: {
        plaName: '',
        plaGender: '',
        plaDepartment: '',
        plaState: '',
        plaAvatar: '',
        plaPhoto:''
      },
      path2:"",
      jwtToken: localStorage.getItem("jwtToken"),
      rules: {
        plaName: [
          { required: true, message: '请输入选手姓名', trigger: 'blur' }
        ],
        plaGender: [
          { required: true, message: '请选择性别', trigger: 'change' }
        ],
        plaDepartment: [
          { required: true, message: '请选择部门', trigger: 'change' }
        ],
        plaState: [
          { required: true, message: '请选择状态', trigger: 'change' }
        ],
        plaAvatar: [
          { required: true, message: '请上传头像', trigger: 'change' }
        ],
        plaPhoto: [
          { required: true, message: '请上传头像', trigger: 'change' }
        ]
      }
    }
  },
  created() {
    this.load();
  },
  methods: {
    handleAvatarSuccess(res) {
      
      if (res && res.code === 200) {
        this.form.plaAvatar = config.apiUrl + res.content;
        this.$refs.formRef.validateField('plaAvatar');
        this.$forceUpdate();
      } else {
        this.$message.error('上传失败');
      }
    },
    handleAvatarSuccess1(res) {
      if (res && res.code === 200) {
        this.path2 =  config.apiUrl +  res.content;
        this.form.plaPhoto = this.path2
        this.$refs.formRef.validateField('plaPhoto');
        this.$forceUpdate();
  
      } else {
        this.$message.error('上传失败');
      }
    },
    beforeUpload(file) {
      const isJPGOrPNG = file.type === 'image/jpeg' || file.type === 'image/png';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPGOrPNG) {
        this.$message.error('只能上传 JPG 或 PNG 格式的图片!');
      }
      if (!isLt2M) {
        this.$message.error('图片大小不能超过 2MB!');
      }

      return isJPGOrPNG && isLt2M;
    },
    load() {
      request.get("/player/list").then(res => {
        if (res.code === 1) {
          this.tableData = res.data;
        } else {
          this.$message.error(res.msg);
        }
      })
    },
    startScore(row) {
      sessionStorage.setItem('player_current_plaName', row.plaName);
      sessionStorage.setItem('player_current_plaDepartment', row.plaDepartment);
      sessionStorage.setItem('player_current_plaAvatar', row.plaAvatar);
      this.$router.push("/xsscore").then(() => {
        this.enterFullScreen();
      });
    },
    enterFullScreen() {
      const element = document.documentElement; // 获取整个文档元素
      if (element.requestFullscreen) {
        element.requestFullscreen();
      } else if (element.mozRequestFullScreen) { // Firefox
        element.mozRequestFullScreen();
      } else if (element.webkitRequestFullscreen) { // Chrome, Safari and Opera
        element.webkitRequestFullscreen();
      } else if (element.msRequestFullscreen) { // IE/Edge
        element.msRequestFullscreen();
      }
    },
    add() {
      this.form = {};
      this.dialogFormVisible = true;
    },
    edit(obj) {
      this.form = { ...obj };
      this.dialogFormVisible = true;
    },
    del(id) {
      request.delete(`/player/${id}`).then(res => {
        if (res.code === 1) {
          this.tableData = this.tableData.filter(item => item.id !== id);
          this.$message({
            message: '删除成功',
            type: 'success'
          });
        } else {
          this.$message({
            message: res.msg,
            type: 'error'
          });
        }
      })
    },
    submit() {
      this.$refs.formRef.validate((valid) => {
        if (valid) {
          request.post("/player/save", this.form).then(res => {
            if (res.code === 1) {
              this.$message({
                message: '操作成功',
                type: 'success'
              });
              this.dialogFormVisible = false;
              this.load();
            } else {
              this.$message({
                message: res.msg,
                type: 'error'
              });
            }
          });
        } else {
          return false;
        }
      });
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
    },
    formatter(row, column) {
      return row.address;
    }
  }
}
</script>

<style scoped>
.el-dialog {
  border-radius: 10px;
  /* 圆角边框 */
}

.el-form {
  padding: 20px;
  /* 增加表单内边距 */
}

.el-form-item {
  margin-bottom: 20px;
  /* 增加表单项之间的间距 */
}

.el-form-item__label {
  font-weight: bold;
  /* 加粗标签文字 */
}

.el-form-item__content {
  display: flex;
  align-items: center;
  /* 垂直居中对齐 */
}

.el-form-item__error {
  color: red;
  /* 统一错误提示颜色 */
  font-size: 12px;
  /* 统一错误提示字体大小 */
  line-height: 1.2;
  /* 统一错误提示行高 */
  position: absolute;
  /* 绝对定位，确保错误提示显示在表单项下方 */
  top: 100%;
  /* 确保错误提示显示在表单项下方 */
  left: 0;
  /* 左对齐 */
  padding-top: 4px;
  /* 上边距 */
}

.el-form-item.is-error .el-input__inner {
  border-color: red;
  /* 输入框错误时的边框颜色 */
}

.el-form-item.is-error .el-select .el-input__inner {
  border-color: red;
  /* 下拉选择框错误时的边框颜色 */
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  line-height: 100px;
  text-align: center;
}

.avatar {
  width: 100px;
  height: 100px;
  display: block;
}
</style>